package com.xc.btc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xc.btc.util.HttpClient;
import org.bitcoinj.core.Base58;
import org.bitcoinj.core.DumpedPrivateKey;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.params.MainNetParams;
import org.spongycastle.util.encoders.Hex;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@SpringBootApplication
public class BtcApplication {

    public static void main(String[] args) {
        System.out.println(new Date().getTime());
        String s = "test";//原始的助记词
        String md5Str = DigestUtils.md5DigestAsHex(s.getBytes());
        getBTC(md5Str);
    }

    private static void getBTC(String s){
        System.out.println();
        System.out.println("######################## BTC ##############################");
        String hex = SHA256(s);
        System.out.println("原始16进制格式私钥:"+hex);
        System.out.println("WIF格式私钥:"+getWIF(hex));
        System.out.println("WIF压缩格式私钥："+getWIF(hex+"01"));
        String address = getAddress(getWIF(hex+"01"));
        System.out.println("对应普通地址:"+address);
        Integer blance = getblance(address);
        System.out.println("对应余额："+blance);
        System.out.println("######################## BTC ##############################");
        System.out.println();
        System.out.println();
    }

    private static String getWIF(String hex){
        //1.在16进制私钥前面加上0x80版本号
        hex = "80"+hex;
        //2.对第1步结果进行SHA256哈希计算
        byte[] hash1 = Sha256Hash.hash(Hex.decode(hex));
        //3.将第2步结果进行SHA256哈希计算
        byte[] hash2 = Sha256Hash.hash(hash1);
        //4.取第3步结果的前4字节(c47e83ff)，加到第1步结果的末尾
        String result = hex + Hex.toHexString(hash2).substring(0, 8);
        //5.对第4步结果进行Base58编码
        return Base58.encode(Hex.decode(result));
    }

    public static String SHA256(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (Exception e) {
            System.out.println("getSHA256 is error" + e.getMessage());
        }
        return encodeStr;

    }

    private static String byte2Hex(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        String temp;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                builder.append("0");
            }
            builder.append(temp);
        }
        return builder.toString();
    }

    private static String getAddress(String privateKey){
        DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(MainNetParams.get(), privateKey);
        ECKey ecKey = dumpedPrivateKey.getKey();
        System.out.println("公钥key："+ecKey.getPublicKeyAsHex());
        return ecKey.toAddress(MainNetParams.get()).toBase58();
    }

    private static Integer getblance(String adress){
        String url = "https://explorer.api.btc.com/search/";
        Map map = new LinkedHashMap();
        map.put("app_a","S2Q4QUljMHEwNzNoMAI5XdXXMAgwqxia4P8VScnvddXEG5EguXvUEXk4ccTC");
        map.put("app_b","Kd8AIc0q073h0");
        map.put("nonce","DJI22151IXIC7512");
        map.put("timestamp",(new Date().getTime()+"").substring(0,10));
        map.put("q",adress);
        map.put("coins","btc,bch,ltc,eth");
        map.put("sign","m9WBCZyVrs8GlHFYx3ezVoYc5JTDIuG7wSvH57uyKeY=");
        String result = HttpClient.doGet(url, map);
        System.out.println("查询返回："+result);
        JSONObject json = JSON.parseObject(result);
        JSONObject data = json.getJSONObject("data");
        JSONArray list = data.getJSONArray("list");
        Integer balance = 0;
        for(int i = 0; i<list.size() ; i++){
            if("btc".equals(list.getJSONObject(i).getString("coin"))){
                String balanceStr = list.getJSONObject(i).getJSONObject("extra_values").getJSONObject("address").getString("balance");
                System.out.println("查询余额:"+balanceStr);
                balance = Integer.parseInt(balanceStr);
            }
        }
        return balance;
    }

}
